17.1 Skills 开发环境搭建

12 分钟阅读

开发环境概述#

开发 Skills 需要搭建合适的开发环境,包括必要的工具、依赖和配置。本节将详细介绍如何搭建 Skills 开发环境。

环境要求#

1. 系统要求#

系统要求#

操作系统#

  • Linux(推荐 Ubuntu 20.04+)
  • macOS 10.15+
  • Windows 10+(需要 WSL2)

硬件要求#

  • CPU: 4 核心及以上
  • 内存: 8GB 及以上(推荐 16GB)
  • 磁盘: 20GB 可用空间

软件要求#

  • Python 3.8+
  • Node.js 16+(可选,用于前端开发)
  • Git 2.20+
  • Docker 20+(可选,用于容器化)

2. 开发工具#

推荐开发工具#

代码编辑器#

  • VS Code(推荐)
  • PyCharm
  • Sublime Text

版本控制#

  • Git
  • GitHub Desktop(可选)

调试工具#

  • Python Debugger (pdb)
  • VS Code Debugger

测试工具#

  • pytest
  • unittest
  • coverage.py

环境安装#

1. Python 环境安装#

1.1 安装 Python

bash
# macOS brew install python@3.9 # Ubuntu/Debian sudo apt update sudo apt install python3.9 python3.9-venv python3-pip # Windows # 从 https://www.python.org/downloads/ 下载安装程序

1.2 创建虚拟环境

bash
# 创建虚拟环境 python3 -m venv venv # 激活虚拟环境 # macOS/Linux source venv/bin/activate # Windows venv\Scripts\activate

1.3 安装依赖

bash
# 创建 requirements.txt cat > requirements.txt << EOF claude-code>=1.0.0 pytest>=7.0.0 pytest-cov>=4.0.0 black>=23.0.0 pylint>=2.17.0 mypy>=1.0.0 EOF # 安装依赖 pip install -r requirements.txt

2. Claude Code SDK 安装#

2.1 安装 SDK

bash
# 安装 Claude Code SDK pip install claude-code-sdk # 验证安装 claude --version

2.2 配置 SDK

bash
# 创建配置目录 mkdir -p ~/.claude # 创建配置文件 cat > ~/.claude/config.yaml << EOF version: "1.0" skills: development: enabled: true auto_reload: true log_level: DEBUG sdk: api_key: your_api_key_here endpoint: https://api.claudecode.com EOF

3. 开发工具安装#

3.1 VS Code 扩展

推荐安装的 VS Code 扩展#

  • Python
  • Pylance
  • Black Formatter
  • Pylint
  • pytest
  • GitLens
  • Docker

3.2 配置 VS Code

json
{ "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python", "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.formatting.provider": "black", "python.testing.pytestEnabled": true, "python.testing.pytestArgs": [ "tests" ], "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.organizeImports": true } }

项目初始化#

1. 创建项目结构#

bash
# 创建项目目录 mkdir my-skill cd my-skill # 创建项目结构 mkdir -p src/skills mkdir -p tests mkdir -p docs mkdir -p examples mkdir -p scripts

2. 初始化项目#

2.1 创建 setup.py

python
# setup.py from setuptools import setup, find_packages setup( name="my-skill", version="0.1.0", description="A custom Claude Code skill", author="Your Name", author_email="your.email@example.com", packages=find_packages(where="src"), package_dir={"": "src"}, python_requires=">=3.8", install_requires=[ "claude-code-sdk>=1.0.0", ], extras_require={ "dev": [ "pytest>=7.0.0", "pytest-cov>=4.0.0", "black>=23.0.0", "pylint>=2.17.0", "mypy>=1.0.0", ] }, entry_points={ "claude.skills": [ "my_skill = skills.my_skill:MySkill", ] } ) ~~~ #### 2.2 创建 pyproject.toml ```toml # pyproject.toml [build-system] requires = ["setuptools>=45", "wheel", "setuptools_scm>=6.2"] [project] name = "my-skill" version = "0.1.0" description = "A custom Claude Code skill" authors = [ {name = "Your Name", email = "your.email@example.com"} ] requires-python = ">=3.8" dependencies = [ "claude-code-sdk>=1.0.0", ] [project.optional-dependencies] dev = [ "pytest>=7.0.0", "pytest-cov>=4.0.0", "black>=23.0.0", "pylint>=2.17.0", "mypy>=1.0.0", ] [project.entry-points."claude.skills"] my_skill = "skills.my_skill:MySkill" [tool.black] line-length = 88 target-version = ['py38'] [tool.pylint.messages_control] disable = [ "C0111", # missing-docstring ] [tool.pytest.ini_options] testpaths = ["tests"] python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"]

2.3 创建 README.md

markdown
# My Skill A custom Claude Code skill for demonstrating skill development. ## Installation ```bash pip install my-skill

Usage#

bash
claude --skill my-skill --param value

Development#

bash
# Install development dependencies pip install -e ".[dev]" # Run tests pytest # Run linting pylint src/skills # Format code black src/skills

License#

MIT

bash
~~~
### 3. 创建基础 Skill

#### 3.1 创建 Skill 文件

```python
# src/skills/my_skill.py
from typing import Dict, Any
from claude_code_sdk import Skill, SkillContext, SkillResult

class MySkill(Skill):
    def __init__(self):
        super().__init__(
            name="my-skill",
            version="0.1.0",
            description="A custom Claude Code skill"
        )

    def get_parameters_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "input": {
                    "type": "string",
                    "description": "Input text to process"
                }
            },
            "required": ["input"]
        }

    def execute(self, parameters: Dict[str, Any], context: SkillContext) -> SkillResult:
        input_text = parameters["input"]
        # 处理输入
        output = self.process_input(input_text)
        return SkillResult(
            success=True,
            data={
                "input": input_text,
                "output": output
            }
        )

    def process_input(self, input_text: str) -> str:
        # 实现具体的处理逻辑
        return input_text.upper()
bash
#### 3.2 创建测试文件

```python
# tests/test_my_skill.py
import pytest
from skills.my_skill import MySkill

class TestMySkill:
    def setup_method(self):
        self.skill = MySkill()

    def test_skill_initialization(self):
        assert self.skill.name == "my-skill"
        assert self.skill.version == "0.1.0"

    def test_get_parameters_schema(self):
        schema = self.skill.get_parameters_schema()
        assert "properties" in schema
        assert "input" in schema["properties"]

    def test_execute(self):
        from claude_code_sdk import SkillContext

        parameters = {"input": "hello"}
        context = SkillContext()
        result = self.skill.execute(parameters, context)

        assert result.success
        assert result.data["output"] == "HELLO"

    def test_process_input(self):
        assert self.skill.process_input("hello") == "HELLO"
        assert self.skill.process_input("world") == "WORLD"
```

## 开发配置

### 1. 调试配置

#### 1.1 VS Code 调试配置

```json
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
}
},
{
"name": "Python: pytest",
"type": "python",

"request": "launch", "module": "pytest", "args": [ "tests", "-v" ], "console": "integratedTerminal", "env": { "PYTHONPATH": "${workspaceFolder}/src" } } ] }

bash
~~~
#### 1.2 日志配置

```python
# src/skills/logger.py
import logging
import sys

def setup_logger(name: str, level: int = logging.DEBUG):
    logger = logging.getLogger(name)
    logger.setLevel(level)

    # 创建控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(level)

    # 创建格式化器
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    console_handler.setFormatter(formatter)

    # 添加处理器
    logger.addHandler(console_handler)

    return logger

# 使用示例
logger = setup_logger(__name__)
logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")

2. 测试配置#

2.1 pytest 配置

python
# tests/conftest.py import pytest from claude_code_sdk import SkillContext @pytest.fixture def skill_context(): return SkillContext() @pytest.fixture def sample_parameters(): return { "input": "test input" }
bash
#### 2.2 测试覆盖率配置

```bash
# 运行测试并生成覆盖率报告
pytest --cov=src/skills --cov-report=html --cov-report=term

# 生成覆盖率报告
pytest --cov=src/skills --cov-report=html
open htmlcov/index.html
```

### 3. 代码质量配置

#### 3.1 Black 配置

```ini
# setup.cfg
[tool:pytest]
testpaths = tests

[black]
line-length = 88
target-version = ['py38']
include = '\.pyi?$'
extend-exclude = '''
/(
# directories
\.eggs
| \.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| build
| dist
)/
'''
```

3.2 Pylint 配置

ini
# .pylintrc [MASTER] disable=C0111,C0103 [FORMAT] max-line-length=88 [DESIGN] max-args=7 max-locals=15 max-returns=6 max-branches=12 max-statements=50

3.3 MyPy 配置

ini
# mypy.ini [mypy] python_version = 3.8 warn_return_any = True warn_unused_configs = True disallow_untyped_defs = True [mypy-tests.*] disallow_untyped_defs = False
bash
## 开发工作流
### 1. 开发流程

```markdown
## 开发流程

### 1. 功能开发

### 2. 代码审查

### 3. 发布
```

### 2. Git 工作流

```bash
# 创建功能分支
git checkout -b feature/new-feature

# 提交代码
git add .
git commit -m "Add new feature"

# 推送到远程
git push origin feature/new-feature

# 创建 Pull Request
# 在 GitHub 上创建 PR

# 合并后删除分支
git checkout main
git pull origin main
git branch -d feature/new-feature
git push origin --delete feature/new-feature
```

3. 持续集成#

3.1 GitHub Actions 配置

yaml
# .github/workflows/ci.yml name: CI on: push: branches: [ main, develop ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.9' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -e ".[dev]"
yaml
- name: Lint with pylint run: | pylint src/skills - name: Format check with black run: | black --check src/skills - name: Type check with mypy run: | mypy src/skills - name: Test with pytest run: | pytest --cov=src/skills --cov-report=xml - name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: file: ./coverage.xml

常见问题#

1. 安装问题#

常见安装问题#

问题:pip 安装失败#

解决方案

bash
# 升级 pip pip install --upgrade pip # 使用国内镜像 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple my-skill

问题:依赖冲突#

解决方案

bash
# 使用虚拟环境 python -m venv venv source venv/bin/activate # 使用 pip-tools pip install pip-tools pip-compile requirements.in pip-sync requirements.txt

2. 运行问题#

常见运行问题#

问题:Skill 找不到#

解决方案

bash
# 确认 Skill 已注册 claude skill list # 重新安装 Skill pip install -e . # 检查 PYTHONPATH export PYTHONPATH="${PYTHONPATH}:$(pwd)/src"

问题:权限错误#

解决方案

bash
# 检查文件权限 ls -la # 修改权限 chmod +x scripts/*.sh # 使用 sudo(不推荐) sudo pip install my-skill

3. 调试问题#

常见调试问题#

问题:无法设置断点#

解决方案

python
# 使用 pdb import pdb; pdb.set_trace() # 使用 ipdb import ipdb; ipdb.set_trace() # 使用 VS Code 调试器 # 在代码行号左侧点击设置断点

问题:日志不输出#

解决方案

python
# 确保日志级别正确 logger.setLevel(logging.DEBUG) # 添加处理器 handler = logging.StreamHandler() logger.addHandler(handler) # 检查日志配置 logging.basicConfig(level=logging.DEBUG)

标记本节教程为已读

记录您的学习进度,方便后续查看。